from server_server import RequestHandle
from threading import Thread
from setting import *

"""
接收客户端请求，并将请求解析发后服务端后端
还没有做子线程回收处理, 在这记录下, 别忘了
"""


class ServerClient:
    def __init__(self):
        self.s = socket.socket()
        self.s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)  # 调试用
        self.s.bind(ADDR)
        self.create_listen()

    def create_listen(self):
        self.s.listen(3)

    def wait_user_connect(self):
        self.conn, self.addr = self.s.accept()
        print('用户: %s:%s 进行了链接' % self.addr)

        return self.conn, self.addr

    def msg_recv(self, recv_size=4096):
        try:
            client_msg = self.conn.recv(recv_size)
            if not client_msg:
                return LOGOUT_MARK
            print('请求内容：', client_msg.decode())
        except Exception as e:
            print(e)
            print('客户端 %s:%s 断开连接' % (self.addr))
            return LOGOUT_MARK

        else:
            return client_msg.decode()

    def msg_send(self, msg):
        msg_encode = msg.encode()
        self.conn.send(msg_encode)

    def conn_close(self):
        self.conn.close()

    def sock_close(self):
        self.s.close()

    def close(self):
        self.conn_close()
        self.sock_close()

    def new_conn(self):
        while 1:
            msg = self.msg_recv()
            if msg == LOGOUT_MARK:
                print('线程连接断开')
                return
            request_handle = RequestHandle(msg, self.conn)
            request_handle.main_handle()

            print('请求处理完毕')


def start_forever():
    create_scoket = ServerClient()
    while 1:
        print('等待连接')
        create_scoket.wait_user_connect()
        th = Thread(target=create_scoket.new_conn)
        th.daemon = True
        th.start()


if __name__ == '__main__':
    start_forever()